package me.leiusual.sharing.ui.setting

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_setting_password.*
import me.leiusual.sharing.R
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.util.extension.toast
import timber.log.Timber
import javax.inject.Inject

/**
 * Create by leiusual on 2018/7/21
 */
class SettingPasswordFragment : DaggerFragment() {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val viewModel: SettingPasswordViewModel by viewModels { factory }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_setting_password, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }

    button_confirm.setOnClickListener {
      val passwordOld = edit_text_password_old.text.toString()
      val passwordNew = edit_text_password_new.text.toString()
      val passwordTwo = edit_text_password_two.text.toString()
      viewModel.passwordUpdate(passwordOld, passwordNew, passwordTwo)
    }

    observeData()
  }

  private fun observeData() {
    viewModel.passwordUpdate.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("passwordUpdate = %s", it)
      when (it) {
        is Data.Loading -> {
          button_confirm.isEnabled = false
        }
        is Data.Error -> {
          button_confirm.isEnabled = true
          toast(it.error.message)
        }
        is Data.Success -> {
          toast("密码修改成功")
          findNavController().popBackStack()
        }
      }
    })
  }
}